<template>
  <div class="MyTaskList">
    <el-row>
      <el-col :span="24">
        <el-card>
          <el-form class="form" ref="form" :model="search" :inline="true">
            <el-form-item label="任务名称">
              <el-input v-model="search.planName"></el-input>
            </el-form-item>
            <el-form-item label="任务状态">
              <el-select
                v-model="search.planStatus.value"
                placeholder="请选择任务状态"
                @change="statusChange"
              >
                <el-option
                  v-for="item in search.planStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSearch">查询</el-button>
              <el-button @click="onReset">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <el-card class="el-card" shadow="never">
          <el-table :data="taskList" style="width: 100%">
            <el-table-column
              fixed
              prop="planName"
              label="任务计划名称"
            ></el-table-column>
            <el-table-column sortable label="开始时间">
              <template slot-scope="scope">
                {{ scope.row.planStartTime | formatDate }}
              </template>
            </el-table-column>
            <el-table-column sortable label="结束时间">
              <template slot-scope="scope">
                {{ scope.row.planEndTime | formatDate }}
              </template>
            </el-table-column>

            <el-table-column label="任务状态">
              <template slot-scope="scope">{{
                planStatusCn(scope.row.planStatus)
              }}</template>
            </el-table-column>

            <el-table-column
              prop="planRequire"
              label="计划要求"
            ></el-table-column>

            <el-table-column label="操作" fixed="right">
              <template slot-scope="scope">
                <!-- //  1:未发布 = 发布 2:已发布 = 撤回 3:已撤回 = 发布 4:已启用 = 停用 5：已停用 = 启用 -->

                <!-- <el-button type="text" size="small">发布{{scope.row.planStatus}}</el-button> -->
                <el-button
                  @click="showClick(scope.row.id)"
                  type="text"
                  size="small"
                  >查看</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="bottom">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="currentchange"
              :current-page="paging.pageNum"
              :page-sizes="[5, 10, 20, 30, 40]"
              :page-size="paging.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="paging.total"
            ></el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!--       :before-close="handleClose" -->
    <el-dialog
      :title="details.planName"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-card shadow="never">
        <!-- {{details}} -->
        <el-form
          :model="details"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="计划名称" prop="planName">
            <el-input
              v-model="details.planName"
              :disabled="disabled"
            ></el-input>
          </el-form-item>
          <el-form-item label="任务状态" prop="planStatus">
            <template v-for="(item, index) in search.planStatus">
              <el-radio
                v-if="index != 0"
                :disabled="disabled"
                :key="index"
                v-model="details.planStatus"
                :label="item.value"
                >{{ item.label }}</el-radio
              >
            </template>
          </el-form-item>

          <el-form-item label="采集区域" required>
            <el-col :span="11">
              <div class="block">
                <el-cascader
                  v-model="area"
                  type="primary"
                  :options="options"
                  :props="props"
                  collapse-tags
                  @change="changecollectTaskTown"
                ></el-cascader>
              </div>
            </el-col>
          </el-form-item>

          <el-form-item label="采集时间" required>
            <el-col :span="11">
              <el-form-item prop="planStartTime">
                <el-date-picker
                  type="datetime"
                  :disabled="disabled"
                  placeholder="采集任务开始时间"
                  v-model="details.planStartTime"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="2" style="text-align: center">-</el-col>
            <el-col :span="11">
              <el-form-item prop="planEndTime">
                <el-date-picker
                  type="datetime"
                  :disabled="disabled"
                  placeholder="采集任务结束时间"
                  v-model="details.planEndTime"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-form-item>

          <el-form-item label="采集要求">
            <el-input
              type="textarea"
              :disabled="disabled"
              class="textarea"
              v-model="details.planRequire"
            ></el-input>
          </el-form-item>

          <el-form-item label="图片">
            <el-image
              style="width: 120px; margin: 5px"
              v-for="item in details.ossImgList"
              :disabled="disabled"
              fit="fill"
              :key="item.id"
              :src="item.imgUrl"
            ></el-image>
          </el-form-item>
        </el-form>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import {
  formatDate
} from "@/library";
import {
  mapGetters
} from "vuex";
import {
  convertKey,
  editDisplay
} from "@/library";
export default {
  name: "TaskPlanningList",
  data() {
    return {
      treeDataProps: {
        children: "children",
        value: "administrativeCode",
        label: "administrativeName",
      },
      area: [
        ["440605011", "440605011002"]
      ],
      props: {
        multiple: true,
      },
      ruleForm: {},
      search: {
        planName: "",
        planStatus: [{
          value: "",
          label: "全部",
        },
        {
          value: 1,
          label: "未发布",
        },
        {
          value: 2,
          label: "已发布",
        },
        {
          value: 3,
          label: "已撤回",
        },
        ],
        value: "",
      },
      params: {
        pageNumber: 1,
        pageSize: 10,
      },
      paging: {},
      taskList: [],
      dialogVisible: false,
      details: {
        info: {},
        area: "",
      },
      villageMatch: [],
      townMatch: [],
      townVillage: {},
      townVillageCopy: {},
      disabled: true,
      showButton: false,
    };
  },
  created() {
    this.queryMyPlan();
    this.villageInit();
  },
  computed: {
    ...mapGetters({
      options: "getTreeData/filtersVillage",
    }),
  },
  methods: {
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => { });
    },
    statusChange(item) {
      console.log(item);
      if (typeof item === "number") {
        this.params["planStatus"] = item;
      } else {
        delete this.params["planStatus"];
      }
    },
    planStatusCn(index) {
      var planStatus = {
        1: "未发布",
        2: "已发布",
        3: "已撤回",
        4: "已启用",
        5: "已停用",
      };

      return planStatus[index];
    },

    updateStatus(row, planStatus, text) {
      console.log(row.id, planStatus);
      let url = "task/task/updateStatus";
      this.$axios
        .post(url, {
          params: {
            id: row.id,
            planStatus,
          },
        })
        .then((res) => {
          if (res.result === "success") {
            this.queryMyPlan(this.params);
            this.$message.success("计划" + text + "成功");
          }
        });
    },
    closeDetails() {
      this.dialogVisible = false;
    },
    editDetails() {
      this.dialogVisible = false;

      //修改计划提交
      this.$axios
        .post("task/update", {
          params: {
            id: this.details.id,
            planName: this.details.planName,
            area: JSON.stringify(this.townVillage),
            planRequire: this.details.planRequire,
            planStartTime: formatDate(this.details.planStartTime),
            planEndTime: formatDate(this.details.planEndTime),
          },
        })
        .then((res) => {
          if (res.request === "success") {
            this.$message.success("计划修改成功");
          }
        });
    },
    villageInit() {
      this.options.forEach((item) => {
        this.townMatch.push(item.value);
        this.villageMatch.push([
          ...JSON.stringify([item.children]).match(/\d{12}/g),
        ]);
      });
    },
    changecollectTaskTown(e) {
      let newSelect = new Map();
      // ,newSelectTown = [],children;
      e.forEach((item) => {
        let town;
        let townIndex = this.townMatch ?.indexOf(item[0]);
        let villageIndex = this.villageMatch[townIndex] ?.indexOf(item[1]);
        town = JSON.parse(JSON.stringify(this.options[townIndex]));
        town.children = [
          JSON.parse(
            JSON.stringify(this.villageMatch[townIndex][villageIndex])
          ),
        ];

        if (newSelect.get(town.value)) {
          newSelect.get(town.value).children = [
            ...newSelect.get(town.value).children,
            ...town.children,
          ];
        } else {
          newSelect.set(town.value, town);
        }
      });
      newSelect.forEach((item, key) => {
        // newSelectTown.push(item);
        this.townVillage[key] = item.children;
      });
      console.log(JSON.stringify(this.townVillage));
      // this.townVillage = newSelectTown;
    },
    showClick(id) {
      this.handleClick(id);
      this.disabled = true;
    },
    handleClick(id) {
      this.disabled = false;
      this.showButton = true;
      this.$axios
        .get("task/task/getAListOfPlans/", {
          params: {
            "planInfo.id": id,
          },
        })
        .then((res) => {
          this.details = res.data.list[0];
          let treeData = this.details ?.treeData ?.treeItem[0] ?.children;
          let options;
          if (typeof treeData != "undefined") {
            options = convertKey(treeData, {
              administrativeName: "label",
              administrativeCode: "value",
            });
            this.details.options = options;
          } else {
            this.details.options = [];
          }
          // console.log(JSON.stringify(options,['label','value','children'])
          //构建 areas 回显数据
          this.area = editDisplay(this.details.treeData.list);

          delete this.details.treeData;
          this.dialogVisible = true;
        });
    },
    onSearch() {
      this.params.keywords = this.search.planName.trim();
      this.queryMyPlan(this.params);
    },
    onReset() {
      this.search = {
        planName: "",
        planStatus: [{
          value: "",
          label: "全部",
        },
        {
          value: 1,
          label: "未发布",
        },
        {
          value: 2,
          label: "已发布",
        },
        {
          value: 3,
          label: "已撤回",
        },
        {
          value: 4,
          label: "已启用",
        },
        {
          value: 5,
          label: "已停用",
        },
        ],
        value: "",
      };
      delete this.params["planStatus"];
    },
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.queryMyPlan(this.params);
    },
    currentchange(pageNumber) {
      this.params.pageNumber = pageNumber;
      this.queryMyPlan(this.params);
    },
    queryMyPlan(params) {
      this.$fishing.queryMyPlan(params).then((res) => {
        this.taskList = res.data.list;
        delete res.data.list;
        this.paging = res.data;
      });
    },
  },
};
</script>

<style lang="scss">
.TaskPlanningList {
  .form {
    padding: 15px 10px;
  }

  .el-card {
    width: 98%;
    margin: 15px auto 0;

    .bottom {
      display: flex;
      justify-content: flex-end;
      margin-top: 15px;
    }
  }
}
</style>
